package dao;



import exception.NotMatchException;
import model.Makeup;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class MakeupTableDao {

    private MakeupTableDao() {
    }

    public static List<Makeup> getMakeups() throws SQLException {
        List<Makeup> list = new ArrayList<>();

        String sql = "select student.s_no,student.s_name,score.c_name,score.makeup_score " +
                "from student,score " +
                "where student.s_no=score.s_no and score.final_score<60";

        PreparedStatement stmt = Dao.getConnection().prepareStatement(sql);
        ResultSet rs = stmt.executeQuery();

        while (rs.next()) {
            String sno = rs.getString(rs.findColumn("s_no"));
            String sname = rs.getString(rs.findColumn("s_name"));
            String cname = rs.getString(rs.findColumn("c_name"));
            int makeupScore = rs.getInt(rs.findColumn("makeup_score"));

            Makeup makeup = new Makeup();
            makeup.setSno(sno);
            makeup.setSname(sname);
            makeup.setCname(cname);
            makeup.setMakeupScore(makeupScore);

            list.add(makeup);
        }

        return list;
    }

    public static void saveMakeups(List<Makeup> makeups) throws Exception {
        int rowIndex = 0;
        try {
            while (rowIndex < makeups.size()) {
                Makeup makeup = makeups.get(rowIndex);
                saveMakeup(makeup);
                rowIndex++;
            }
        } catch (NotMatchException e) {
            throw new NotMatchException("第 " + rowIndex + " 行，" + e.getMessage());
        }
    }

    public static void saveMakeup(Makeup makeup) throws Exception {
        String sno = makeup.getSno();
        String sname = makeup.getSname();
        String cname = makeup.getCname();
        int makeupScore = makeup.getMakeupScore();

        Dao.checkMatch(sno, sname, cname);

        String sql = "Update score " +
                "set makeup_score=? " +
                "where s_no=? and c_name=?";
        PreparedStatement stmt = Dao.getConnection().prepareStatement(sql);

        stmt.setInt(1, makeupScore);
        stmt.setString(2, sno);
        stmt.setString(3, cname);


        stmt.execute();
    }
}
